package core

import (
	"fmt"
	_ "github.com/coreos/bbolt"
	"github.com/kataras/iris/sessions"
	"github.com/kataras/iris/sessions/sessiondb/boltdb"
	"os"
	"strconv"
	"sync"
	"time"
	"github.com/kataras/iris/context"
)

var (
	manager  *sessions.Sessions
	onceCall sync.Once
	sessionDb *boltdb.Database
)

//在BootConfig.init 方法中初始化
func InitSession()   {
	onceCall.Do(func() {
		initSessionOnce()
	})
}

func initSessionOnce()  {
	config := GetServerConfig()
	sessionId := config.SessionCookieId
	if len(sessionId) == 0 {
		sessionId = "gosessionid"
	}
	minute := time.Duration(config.SessionExpires)
	if minute < 1 {
		minute = 20
	}
	sessionDb, _ = boltdb.New("./cache/sessions.db", os.FileMode(boltdb.DefaultFileMode))
	manager = sessions.New(sessions.Config{
		Cookie:  sessionId,
		Expires: minute * time.Minute,
	})
	manager.UseDatabase(sessionDb)
}

func StartSession(ctx context.Context) *sessions.Session {
	InitSession()
	return manager.Start(ctx)
}

func SetCurrentUser(sess *sessions.Session, user Userinfo) {
	sess.Set(SESSION_USER, user)
}

//清空缓存
func AbandonSession(sess *sessions.Session) {
	sess.Destroy()
}

//获取当前登录用户缓存信息
func CurrentUser(sess *sessions.Session) *Userinfo {
	data := sess.Get(SESSION_USER)
	if data == nil {
		user := Userinfo{}
		return &user
	}
	user, ok := data.(Userinfo)
	if !ok {
		usermap, ok2 := data.(map[string]interface{})
		if !ok2 {
			Logger().Debugf("用户缓存类型无效：%v", data)
			sess.Set(SESSION_USER, nil)
			user = Userinfo{}
		} else {
			tmpuid := usermap["Uid"]
			var (
				uid      int
				uidFloat float64
			)
			uid, ok = tmpuid.(int)
			if !ok {
				uidFloat, ok = tmpuid.(float64)
				if ok {
					uid = int(uidFloat)
				} else {
					uidstr := fmt.Sprintf("%v", tmpuid)
					uid, _ = strconv.Atoi(uidstr)
				}
			}
			username := usermap["Username"]
			user = Userinfo{
				Uid:      uid,
				Username: username.(string),
			}
		}
	}
	return &user
}

type Userinfo struct {
	Uid      int
	Username string
}
